package com.piece.core.log.config;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.piece.core.log.client.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

/**
 * 登录用户信息线程
 */
@Slf4j
public class UserContextHolder {

    /**
     * 支持父子线程之间的数据传递
     */
    private static final ThreadLocal<UserDTO> CONTEXT = new TransmittableThreadLocal<>();

    public static void set(UserDTO user) {
        Assert.notNull(user, "Only non-null UserDTO instances are permitted");
        CONTEXT.set(user);
    }

    public static UserDTO get() {
        return CONTEXT.get();
    }

    public static String getUserId() {
        return get() != null ? get().getId() : "";
    }

    public static String getUserName() {
        return get() != null ? get().getName() : "";
    }

    public static String getUserAvatar() {
        return get() != null ? get().getAvatar() : "";
    }

    public static String getDeptId() {
        return get() != null ? get().getDeptId() : "";
    }

    public static String getDeptName() {
        return get() != null ? get().getDeptName() : "";
    }

    public static void clear() {
        CONTEXT.remove();
    }
}
